#include "Light.h"
#include "MathLib.h"
#include "Tree.h"
#include <stdlib.h>

PointLight::PointLight()
: Light() 

{};

flt PointLight::GetLightContribution(math::Vertex p_vIntersectPt, Tree* p_pTree)
{
	Vector vLight(m_vPosition[0] - p_vIntersectPt.data[0],
					m_vPosition[1] - p_vIntersectPt.data[1],
					m_vPosition[2] - p_vIntersectPt.data[2]);

	vLight.Normalize();

	CollisionInfo shadowInfo = p_pTree->RecursiveRayTreeTraversalB(p_vIntersectPt, vLight, vLight.Length());
	
	if(shadowInfo.pObject == 0)
	{
		return 1.0f;
	}
	else
	{
		return 0.0f;
	}
}

AreaLight::AreaLight()
: Light() 
, m_fLength(0.0f)

{};


flt AreaLight::GetLightContribution(math::Vertex p_vIntersectPt, Tree* p_pTree)
{
	int samples = 16 * 1;
	
	flt fLightCoeff = 0.0f;
	math::Vertex vStartCorner(m_vPosition.data[0] - m_fLength/2.0f, m_vPosition.data[1] , m_vPosition.data[2] - m_fLength/2.0f);
	flt fDelta = m_fLength / 4.0f;

	for(int i = 0; i < samples; i++)
	{
		int iSampleIndex = i % 16;
		int row = iSampleIndex / 4;
		int column = iSampleIndex % 4;
		
		math::Vertex vSample(vStartCorner.data[0] + fDelta * column + ((flt)rand() / (flt)RAND_MAX) * fDelta
							, vStartCorner.data[1]
							, vStartCorner.data[2] + fDelta * row + ((flt)rand() / (flt)RAND_MAX) * fDelta); 

		Vector vLight(vSample[0] - p_vIntersectPt.data[0],
					vSample[1] - p_vIntersectPt.data[1],
					vSample[2] - p_vIntersectPt.data[2]);
							
		flt fLength = vLight.Length();
		vLight.Normalize();

		CollisionInfo shadowInfo = p_pTree->RecursiveRayTreeTraversalB(p_vIntersectPt, vLight, fLength);

		if(shadowInfo.pObject == 0)
		{
			fLightCoeff += 1.0f;
		}
	}
	return fLightCoeff / (flt)samples;
}